package jsyf.oa.service.importExcel;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import jsyf.oa.dao.apply.MoneyMainDao;
import jsyf.oa.dao.contract.AvailableDao;
import jsyf.oa.dao.contract.FinancingDao;
import jsyf.oa.dao.contract.RepaymentDao;
import jsyf.oa.dao.device.DeviceServiceDao;
import jsyf.oa.dao.report.mineCustomer.CustomerReportDao;
import jsyf.oa.dao.salary.SalaryDetailsDao;
import jsyf.oa.dao.salary.SalaryMainDao;
import jsyf.oa.dao.system.UserDao;
import jsyf.oa.entity.apply.MoneyMainEntity;
import jsyf.oa.entity.contract.AvailableEntity;
import jsyf.oa.entity.contract.FinancingEntity;
import jsyf.oa.entity.contract.RepaymentEntity;
import jsyf.oa.entity.device.DeviceServiceEntity;
import jsyf.oa.entity.report.mineCustomer.CustomerReportEntity;
import jsyf.oa.entity.salary.SalaryDetailsEntity;
import jsyf.oa.entity.salary.SalaryMainEntity;
import jsyf.oa.facade.importExcel.ImportExcelFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by 92852 on 2018/4/19.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class ImportExcelService implements ImportExcelFacade {
    @Autowired
    private DeviceServiceDao deviceServiceDao;
    @Autowired
    private MoneyMainDao moneyMainDao;
    @Autowired
    private FinancingDao financingDao;
    @Autowired
    private AvailableDao availableDao;
    @Autowired
    private RepaymentDao repaymentDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private CustomerReportDao customerReportDao;
    @Autowired
    private SalaryDetailsDao salaryDetailsDao;
    @Autowired
    private SalaryMainDao salaryMainDao;

    @Override
    public String readExcelFile(String jsonData) {
        List<DeviceServiceEntity> entity = JSONObject.parseArray(jsonData, DeviceServiceEntity.class);
        for (int i = 0; i < entity.size(); i++) {
            DeviceServiceEntity model = entity.get(i);
            String companyName = model.getCompanyName();
            String brandName = model.getBrandName();
            String modelName = model.getModelName();
            String deviceTypeName = model.getDeviceTypeName();
            String sequence = model.getSequence();
            StringBuffer condition = new StringBuffer();
            condition.append("SELECT COUNT(1) AS count FROM t_dvc_service \n" +
                    "WHERE 1=1" + "\n");
            condition.append(" AND `COMPANY_NAME`=" + " '" + companyName + "'" + "\n");
            condition.append(" AND `BRAND_NAME`=" + " '" + brandName + "'" + "\n");
            condition.append(" AND `MODEL_NAME`=" + " '" + modelName + "'" + "\n");
            condition.append(" AND `DEVICE_TYPE_NAME`=" + " '" + deviceTypeName + "'" + "\n");
            condition.append(" AND `SEQUENCE`=" + " '" + sequence + "'" + "\n");
            List<JSONObject> records = deviceServiceDao.queryForJsonList(condition.toString(), new Object[]{});
            JSONObject js = records.get(0);
            int count = js.getInteger("count");
            if (count > 0) {
                deviceServiceDao.update(model);
            } else {
                deviceServiceDao.add(model);
            }

        }
        return "true";
    }


    @Override
    public String readExcelMoney(String jsonData) {
        List<MoneyMainEntity> entity = JSONObject.parseArray(jsonData, MoneyMainEntity.class);
        for (int i = 0; i < entity.size(); i++) {
            MoneyMainEntity model = entity.get(i);
            String orgName = model.getOrgName();
            String type = model.getType();
            String title = model.getTitle();
            String SeriesNumber = model.getSeriesNumber();
            StringBuffer condition = new StringBuffer();
            condition.append("SELECT COUNT(1) AS count FROM t_apl_money_main \n" +
                    "WHERE 1=1" + "\n");
            condition.append(" AND `ORG_NAME`=" + " '" + orgName + "'" + "\n");
            condition.append(" AND `TYPE`=" + " '" + type + "'" + "\n");
            condition.append(" AND `TITLE`=" + " '" + title + "'" + "\n");
            condition.append(" AND `SERIES_NUMBER`=" + " '" + SeriesNumber + "'" + "\n");
            List<JSONObject> records = moneyMainDao.queryForJsonList(condition.toString(), new Object[]{});
            JSONObject js = records.get(0);
            int count = js.getInteger("count");
            System.out.println(count);
            if (count > 0) {
                moneyMainDao.update(model);
            } else {
                moneyMainDao.add(model);
            }

        }
        return "true";
    }

    @Override
    public Boolean receivableFile(String jsonData, String mainId, String type) {
        List<RepaymentEntity> list = JSONObject.parseArray(jsonData, RepaymentEntity.class);
        //删除跟踪表中的旧数据
        repaymentDao.removeByCondition(" AND MAIN_ID=? AND TYPE=?", new String[]{mainId, type});
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                RepaymentEntity entity = list.get(i);
                if (StringUtils.isNotEmpty(entity.getRepaymentDate())) {
                    entity.setMainId(mainId);
                    entity.setType(Integer.valueOf(type));
                    entity.setParentId("0");
                    entity.setSortNo(i);
                    entity.setHkType(1);
                    repaymentDao.add(entity);
                }
            }
            return true;
        }
        return false;

    }

    @Override
    public Boolean financingFile(String jsonData, String mainId, String type) {
        List<FinancingEntity> list = JSONObject.parseArray(jsonData, FinancingEntity.class);
        //删除跟踪表中的旧数据
        financingDao.removeByCondition(" AND MAIN_ID=?", new String[]{mainId});
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                FinancingEntity financingEntity = list.get(i);
                if (StringUtils.isNotEmpty(financingEntity.getFinancingDate())) {
                    financingEntity.setMainId(mainId);
                    financingEntity.setParentId("0");
                    financingEntity.setSortNo(i);
                    financingEntity.setType(Integer.valueOf(type));
                    financingEntity.setHkType(1);
                    financingDao.add(financingEntity);
                }
            }
            return true;
        }
        return false;

    }


    @Override
    public String readExcelCustomer(String jsonData, String createName, String createTel) {
        List<CustomerReportEntity> list = JSONObject.parseArray(jsonData, CustomerReportEntity.class);
        int result = 0;
        for (int i = 0; i < list.size(); i++) {
            CustomerReportEntity entity = list.get(i);
            String name = entity.getName();
            String tel = entity.getTel();
            String customerType = entity.getCustomerType();
            String customerCredit = entity.getCustomerCredit();
            String birthday = entity.getBirthday();
            String wechat = entity.getWechat();
            String cityName = entity.getCityName();
            String countryName = entity.getCountyName();
            String existingDevice = entity.getExistingDevice();
            StringBuffer condition = new StringBuffer();
            condition.append("SELECT COUNT(1) AS count FROM t_wrt_customer \n" +
                    "WHERE 1=1" + "\n");
            condition.append(" AND `tel`=" + " '" + tel + "'" + "\n");
            List<JSONObject> records = customerReportDao.queryForJsonList(condition.toString(), new Object[]{});
            JSONObject js = records.get(0);
            int count = js.getInteger("count");
            if (count > 0) {
                result = customerReportDao.updateFromExcle(name, tel, customerType, customerCredit, birthday, wechat, cityName, countryName, existingDevice);
            } else {
                JSONObject jsonUserId = customerReportDao.getIdByNameAndTel(createName, createTel);
                if (jsonUserId != null) {
                    entity.setCreateUserId(jsonUserId.getString("id"));
                    result = customerReportDao.add(entity);
                } else {
                    result = -99;
                }

            }
        }
        if (result > 0) {
            return "true";
        } else if (result == -99) {
            return "noTel";
        } else {
            return "false";
        }
    }

    @Override
    public String readExcelSalary(String jsonData, String month, String fjname) {
        List<SalaryDetailsEntity> list = JSONObject.parseArray(jsonData, SalaryDetailsEntity.class);
        //删除工资字表的旧数据
        salaryDetailsDao.removeByCondition(" AND ATTACH_NAME=? AND MONTH=?", new String[]{fjname, month});
        int rows = 0;
        for (int i = 0; i < list.size(); i++) {
            SalaryDetailsEntity entity = list.get(i);
            String name = entity.getUserName();
            if (StringUtils.isNotEmpty(name)) {
                String card = entity.getCard();
                entity.setAttachName(fjname);
                List<JSONObject> item = userDao.getViewJSONListByCondition("AND main=1 AND name = ?  AND card = ? ", new Object[]{name, card});
                if (item != null && item.size() > 0) {
                    entity.setUserId(item.get(0).getString("id"));
                    entity.setDepartId(item.get(0).getString("departId"));
                    entity.setCompanyId(item.get(0).getString("companyId"));
                    entity.setCompanyName(item.get(0).getString("companyName"));
                    entity.setDepartName(item.get(0).getString("departName"));
                    entity.setRoleName(item.get(0).getString("roleName"));
                }
                rows = salaryDetailsDao.add(entity);
            }
        }
        if (rows > 0) {
            return "true";
        } else if (rows == -99) {
            return "noTel";
        } else {
            return "false";
        }
    }

    @Override
    public Boolean availableFile(String jsonData, String mainId) {
        List<AvailableEntity> list = JSONObject.parseArray(jsonData, AvailableEntity.class);
        //删除跟踪表中的旧数据
        availableDao.removeByCondition(" AND MAIN_ID=?", new String[]{mainId});
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                AvailableEntity availableEntity = list.get(i);
                if (StringUtils.isNotEmpty(availableEntity.getAvailableDate())) {
                    availableEntity.setCreateUserId("2018072410074E31BDA9D2DDCC10562B");
                    availableEntity.setCreateUserName("袁一鸣");
                    availableEntity.setMainId(mainId);
                    availableDao.add(availableEntity);
                }
            }
            return true;
        }
        return false;
    }

}
